package config2excel.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.swing.table.AbstractTableModel;

public class C2ETableModel extends AbstractTableModel {
  /**
   * 
   */
  private static final long serialVersionUID = 1L;

  private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

  private List<Map> data = new ArrayList();

  private String[] columns;

  private String[] columnDisplays;

  public C2ETableModel(String[] columns, String[] columnDisplays) {
    this.columns = columns;
    this.columnDisplays = columnDisplays;
  }

  public List<Map> getData() {
    return data;
  }

  public void setData(List<Map> data) {
    this.data = data;
    fireTableDataChanged();
  }

  @Override
  public int getRowCount() {
    return data.size();
  }

  /**
   * 有隐藏列，所以使用columnDisplays的长度， 在没有隐藏列的情况下使用column和columnDisplays一样
   */
  @Override
  public int getColumnCount() {
    return columnDisplays.length;
  }

  @Override
  public String getColumnName(int column) {
    return columnDisplays[column];
  }

  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
    Map row = data.get(rowIndex);
    Object val = row.get(columns[columnIndex]);
    if (val instanceof Date) {
      val = dateFormat.format((Date) val);
    }
    return val;
  }

  @Override
  public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    // 输入空字符串当null处理
    if (aValue != null && aValue.toString().trim().equals("")) {
      aValue = null;
    }
    Map row = data.get(rowIndex);
    row.put(columns[columnIndex], aValue);
    fireTableCellUpdated(rowIndex, columnIndex);
  }

  public void setValueAt(Object aValue, int rowIndex, String fieldCode) {
    if (aValue != null && aValue.toString().trim().equals("")) {
      aValue = null;
    }
    Map row = data.get(rowIndex);
    row.put(fieldCode, aValue);
    fireTableDataChanged();
  }

  public void addNewRow(Map row) {
    int idx = data.size();
    data.add(idx, row);
    fireTableRowsInserted(idx, idx);
  }

  protected String getOrderByColumn() {
    return "SEQU_NO";
  }

  protected void updateSequNo(List<Map> data) {
    int i = 1;
    for (Map obj : data) {
      obj.put(getOrderByColumn(), i++);
    }
  }

  protected void updateOrderByColumn(int from, int to) {
    for (int i = from; i < to; i++) {
      Map obj = data.get(i);
      obj.put(getOrderByColumn(), i + 1);
    }
  }

}
